package com.haiwen.boot.utils;


import com.haiwen.boot.pojo.EmailModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;



public class MailSendUtils {

    private static final Logger logger = LoggerFactory.getLogger(MailSendUtils.class);

    /**
     * 发送者地址
     **/
    private static final String posterAdress = "228943611@qq.com";

    /**
     * 发送者姓名
     **/
    private static final String posterName = "【两分钟有效】";

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private JavaMailSenderImpl javaMailSenderImpl;

    /**
     * 文本发送
     **/
    public void sendEmailAsText(final EmailModel emailModel) {
        MimeMessagePreparator mimeMessagePreparator = mimeMessage -> {
            mimeMessage.setFrom(posterAdress);
            mimeMessage.setRecipients(Message.RecipientType.TO, emailModel.getRecieverEmailAddress());
            mimeMessage.setText("<html><body>"
                    + "hello：" + emailModel.getRecieverName()
                    + "<br>" + "msg：" + emailModel.getEmailContent()
                    + "<br>" + posterName
                    + "</body></html>");
        };
        try {
            this.javaMailSender.send(mimeMessagePreparator);
            logger.info("邮箱已返送至[{}]邮箱！", emailModel.getRecieverName());
        } catch (MailException e) {
            logger.error("邮箱异常:[{}]", e);
        }
    }

    /**
     * html 网页发送
     * 该方法为同步方法
     **/
    public void sendEmailAsSysExceptionHtml(final EmailModel emailModel) throws MessagingException {
        MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
        MimeMessageHelper mimeMessageHelper;
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom("2289436110@qq.com");
            mimeMessageHelper.setTo(emailModel.getRecieverEmailAddress());
            mimeMessageHelper.setSubject(emailModel.getEmailTheme());
            mimeMessageHelper.setText("<html><body>"
                            + "您好：" + emailModel.getRecieverName()
                            + "," + "本次验证码为：" + emailModel.getEmailContent()
                            + "</br>" + "from :" + posterName
                            + "</body></html>",true);

            this.javaMailSender.send(mimeMessage);
            logger.info("邮箱已返送至[{}]邮箱！", emailModel.getRecieverName());
    }

}
